package com.mystudy.leetcode.problem.math.p_258;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @program: infoalgorithm
 * @description: 各位相加，应使用数学公式做题而非循环或者递归
 * @author: zhouzhilong
 * @create: 2019-07-10 16:53
 **/
public class Solution {
    /**
     * logger
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(Solution.class);

    @Test
    public void test() {
        int result = addDigits(567);
        LOGGER.debug("result:{}", result);

        result = mathMethod(567);
        LOGGER.debug("result:{}", result);
    }

    public int addDigits(int num) {
        while (num > 9) {
            num = add(num);
        }
        return num;
    }

    /**
     * 最普通的递归，效率很低
     *
     * @param digit
     * @return
     */
    private int add(int digit) {
        if (digit < 10) {
            return digit;
        }
        return digit % 10 + add(digit / 10);
    }

    /**
     * 数据定理：9余数定理{result = (digit-1)%9 +1,result !=0}
     * @param num
     * @return
     */
    public int mathMethod(int num) {
        if (num == 0) {
            return 0;
        }
        return (num - 1) % 9 + 1;
    }

}
